// pages/userInfoCenter/index.js

const App = getApp();
const {Dialog, Toast} = require("../../../../../../config/modal")
const utils = require("../../../../../../utils/util")
const {LOCATION} = require("../../../../../../config/login.js")

Page({
    /**
     * 页面的初始数据
     */
    data: {
        title: "发布二手物品",
        theamTextColor: App.globalData.theamTextColor,
        capsuleBarHeight: App.$getMenuButtonHeight(),
        file: {
            maxSize: 5242880,
            maxCount: 9,
            list: []
        },
        product: {
            id: '',
            description: "",
            productNo: "",
            productName: "",
            price: 0,
            typeNo: "",
            stock: 1,
            images: '',
            city: '',
            schoolName: '',
        },
        typeName: '',
        productType: [],
        deleteImgIds: [],
        showPopup: false,
        startDongTai: App.$getActionFlag(),
        
    },
    URL: {
        save: "/product/save",
        update: "/product/update",
        productType: "/product/productTypes",
        getByNo: "/product/edit/?",
        deleteImg: "/product/delete/img/?",
    },
    page: {
        schoolPage: "/pages/school/index",
        product: '/pages/tabbar/user/userInfoCenter/myProduct/index'
    },

    

    initProductType() {
        App.$get(true, this.URL.productType, {}, res => {
            if (res.R) {
                this.setData({
                    productType: res.data,
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.hideShareMenu();
        this.initUserInfo();
        this.initProductType();
        this.edit(options);
        this.setData({
            startDongTai:App.$getActionFlag()
        })
    },
    onShow() {
    },
    edit(options) {
        let productNo = options.productNo;
        if (utils.isInvalid(productNo)){
            return;
        }
        App.$get(true, this.URL.getByNo.replace("?", productNo), {}, res => {
            let p = this.data.product;
            let obj = res.data;
            for (const pKey in p) {
                p[pKey] = obj[pKey];
            }
            p['images'] = "";

            let imgList = [];
            obj.imageList.forEach(img => {
                imgList.push({url: img.imgUrl+"?choosImage=1", name: img.id});
            })

            this.setData({
                product: p,
                'file.list': imgList
            })

            let that = this;
            setTimeout(() => {
                let types = that.data.productType;
                for (let i = 0; i < types.length; i++) {
                    if (obj.typeNo == types[i].value) {
                        this.setData({
                            typeName: types[i].name
                        })
                    }
                }
            }, 500)
        })

    },

    initUserInfo() {
        let user = App.$getUserInfo();
        this.setData({
            'product.schoolName': user.schoolName,
            'product.city': user.city
        })
    },

    // 获取当前所在位置
    toSelectSchoolName() {
        App.$navigateTo(this.page.schoolPage, false)
    },
    onSchoolNameChange(e) {
        this.setData({
            'product.schoolName': e.detail,
        })
    },

    onChangeFormField(e) {
        let key = 'product.' + utils.getEvent(e).name
        this.setData({
            [key]: e.detail.value == undefined ? e.detail : e.detail.value,
        })
    },


    // 选择地址
    selectType(e) {
        let item = utils.getEvent(e).item;
        this.setData({
            'product.typeNo': item.value,
            typeName: item.name,
        })
        this.closePopup();
    },
    // 清楚地址
    clearAddress() {
        this.setData({
            'product.city': ''
        })
    },

    toSelectProductType() {
        this.setData({
            showPopup: true,
        })
    },

    closePopup() {
        this.setData({
            showPopup: false,
        })
    },

    // 提交地址信息
    submitInfo() {
        // 数字校验
        if (!utils.isInteger(this.data.product.stock)) {
            Toast("请输入正确的数量")
            return;
        }

        if (!utils.checkIsNum(this.data.product.price)) {
            Toast("请输入正确的价格")
            return;
        }

        if (utils.isInvalid(this.data.product.typeNo)) {
            Toast("请选择物品类型")
            return;
        }

        if (utils.isInvalid(this.data.product.productName)) {
            Toast("请选物品类型")
            return;
        }

        if (utils.isInvalid(this.data.product.description)) {
            Toast('需要输入内容哦 😊～');
            return;
        }

        if (utils.isInvalid(this.data.product.id)) {
            // 处理图片 转base64
            let imgs = this.data.file.list
            let imgBase64 = "";
            imgs.forEach(file => {
                imgBase64 += utils.fileToBase64Sync(file.url) + "&&";
            })
            if (utils.isInvalid(imgBase64)) {
                Toast('需要选择图片哦 😊～');
                return;
            }
            this.setData({
                'product.images': imgBase64
            })

            this.save();
            return;
        }
        this.update();
    },

    save() {
        App.$post(true, this.URL.save, this.data.product, res => {
            this.reqResult(res);
        })
    }
    ,
    update() {
        let imgs = this.data.file.list
        let imgBase64 = "";
        imgs.forEach(file => {
            if (file.url.indexOf("?choosImage=1") < 0) {
                imgBase64 += utils.fileToBase64Sync(file.url) + "&&";
            }
        })
        this.setData({
            'product.images': imgBase64
        })

        App.$post(true, this.URL.update, this.data.product, res => {
            this.reqResult(res);
            if (res.R) {
                let imgs = this.data.deleteImgIds;
                if (imgs.length > 0) {
                    let ids = imgs.join(",");
                    App.$delete(false, this.URL.deleteImg.replace("?", ids), {}, res => {
                    })
                }
            }
        })
    }
    ,
    reqResult(res) {
        if (res.R) {
            Dialog.alert({
                message: res.msg,
                width: "250px",
                confirmButtonColor: "#D2691E",
                confirmButtonText: "确定",
            }).then(() => {
                App.$redirectTo(this.page.product, true);
            })
        }
    }
    ,

    // 文件读取前
    fileBefore(event) {
        event.detail.callback(true)
    }

    , fileOversize(event) {
        App.$alert('图片每张只允许5M以内的照片');
    },

    fileDelete(event) {
        let index = event.detail.index;
        let files = this.data.file.list;

        // 记录要删除的
        let deleteImgIds = this.data.deleteImgIds;
        if (!utils.isInvalid(files[index].name)){
            deleteImgIds.push(files[index].name);
        }

        files.splice(index, 1);
        this.setData({
            "file.list": files,
        })
    }

    // 证件选择
    , afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        const files = event.detail.file;
        let sourceFiles = this.data.file.list;
        files.forEach(file => {
            sourceFiles.push({url: file.url, name: ""})
        })
        this.setData({
            "file.list": sourceFiles
        })
    }

    , goBack() {
        wx.navigateBack();
    }

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    , onReady: function () {

    }
    ,


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
    }
    ,

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
    ,

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
